.386
stack segment use16 stack
    db 100 dup(0)
stack ends
code segment use16
    assume cs:code, ss:stack

old_int dw 0, 0
row db 0
col db 30
hint db "already installed$"
format_string db ":$"
endl db 13, 10, '$'
hour db 0, 0, '$'
minute db 0, 0, '$'
second db 0, 0, '$'
temp db 0, '$'
cursor dw 0

debug db "here$"
    
new_proc proc far
    id db "123",0
    push ax
    push bx
    push cx
    pushf
    call dword ptr cs:old_int
    mov cl, 16
    ;get_hour
    mov al, 4   
    out 70h, al  
    jmp $ + 2    
    in al, 71h
    mov bl, al
    ;get_minute
    mov al, 2   
    out 70h, al  
    jmp $ + 2    
    in al, 71h
    mov bh, al
    ;get_second
    mov al, 0   
    out 70h, al  
    jmp $ + 2    
    in al, 71h
    ;cmp
    cmp al, temp
    jz exit
    mov temp, al
    ;copy 
    xor ah, ah
    idiv cl
    add ah, '0'
    add al, '0'
    mov second + 1, ah
    mov second, al
    
    xor ax, ax
    mov al, bh
    idiv cl
    add ah, '0'
    add al, '0'
    mov minute + 1, ah
    mov minute, al

    xor ax, ax
    mov al, bl
    idiv cl
    add ah, '0'
    add al, '0'
    mov hour + 1, ah
    mov hour, al

    ; 10h function
    push ax
    push dx
    mov bh, 0
    mov ah, 3
    int 10h
    mov cursor, dx 
    mov ah, 2
    xor bh, bh
    mov dh, row
    mov dl, col
    int 10h
    pop dx
    pop ax
       
    ;print_hour
    mov ax, code
    mov ds, ax
    mov dx, offset hour
    mov ah, 9h
    int 21h
    mov dx, offset format_string
    mov ah, 9h
    int 21h
    ;print_minute
    mov dx, offset minute
    mov ah, 9h
    int 21h
    mov dx, offset format_string
    mov ah, 9h
    int 21h
    ;print_second
    mov dx, offset second
    mov ah, 9h
    int 21h
    mov dx, offset endl
    mov ah, 9h
    int 21h

    ; 10h function
    mov dx, cursor
    mov ah, 2
    int 10h
    
    exit:
    pop cx
    pop bx
    pop ax
    iret
new_proc endp

start:
push cs
pop ds
;get address
mov ax, 0
mov es, ax
mov ax, es:[4 * 8h]
mov bx, es:[4 * 8h + 2]
mov cs:old_int, ax
mov cs:old_int + 2, bx
;check if installed
mov bx, es:[4 * 8h]
cmp bx, offset new_proc
jnz next
; has installed
push ax
mov ax, code
mov ds, ax
mov dx, offset hint
mov ah, 9h
int 21h
pop ax
jmp exit2
;install
next:
mov dx, offset new_proc
mov ax, 2508h
int 21h
;store in memory
mov dx, 100h
mov ah, 31h
int 21h
exit2:
mov ah, 4ch
int 21h
code ends
end start